package com.sangmo.boot.framework.plugin.dataview.def.types;

import com.sangmo.boot.framework.plugin.dataview.validator.impl.ValidationContext;
import com.sangmo.boot.framework.plugin.dataview.validator.violation.DataViolation;

import java.util.Collection;

public class CollectionType extends BasicType<Collection>{
    private Long min = Long.MIN_VALUE;
    private Long max = Long.MAX_VALUE;


    public CollectionType(String name) {
        super(name);
    }

    public CollectionType(String name, long min, long max) {
        super(name);
        this.min = min;
        this.max = max;
    }

    public Long getMin() {
        return min;
    }

    public void setMin(Long min) {
        this.min = min;
    }

    public Long getMax() {
        return max;
    }

    public void setMax(Long max) {
        this.max = max;
    }

    @Override
    public Object format(Collection value) {
        return value;
    }

    @Override
    public DataViolation validate(ValidationContext.DataFieldSource source, Object bean, String name, Collection value) {

        if (null == value) {
            value = null;
        }
        if (null != min && value.size() < min.intValue()) {
            return new DataViolation(source.root, bean, name, "error.datafield.collection.min", min);
        }

        if (null != max && value.size() > max.intValue()) {
            return new DataViolation(source.root, bean, name, "error.datafield.collection.max", max);
        }

        return null;
    }
}
